//
//  LCNetwork.m
//  LongChain
//
//  Created by FengZi on 2018/3/20.
//  Copyright © 2018年 FengZi. All rights reserved.
//

#import "LCNetwork.h"
#import "LCUserModel.h"
@implementation LCNetwork

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static LCNetwork *network = nil;
    dispatch_once(&onceToken, ^{
        network = [[self alloc]init];
    });
    return network;
}

#pragma mark - - GET 请求
- (void)lc_getNetworkWithURL:(NSString *)url
             responseSuccess:(void (^)(id resultCode, id resultParameter))responseSuccessBlock
                responseFail:(void (^)(id resultCode, NSError *error))responseFailBlock {
    
    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,url];
    [requestURL stringByReplacingOccurrencesOfString:@" " withString:@""];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[self requestToken] forHTTPHeaderField:@"Authorization"];



    NSURLSessionTask *task = [manager GET:requestURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LCLog(@"responseObject = %@",responseObject);
        NSString *resultCode = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if ([resultCode isEqualToString:@"0"]) {
            responseSuccessBlock(resultCode,responseObject);
        }else{
            responseFailBlock(@"-1",nil);

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LCLog(@"error = %@",error);
        responseFailBlock(@1,error);
        [task cancel];

        if ([error.localizedDescription containsString:@"401"]) {
            //  验证错误 重新登录
            
            [UserDefault setObject:nil forKey:@"token"];
            [UserDefault synchronize];

            UIStoryboard *mainStoreBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            id loginVC = [mainStoreBoard instantiateViewControllerWithIdentifier:@"LCLoginVC"];
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = loginVC;
            
            
        }
    }];
    NSLog(@"task = %@",task.originalRequest);
    
}

#pragma mark - - POST 请求
- (void)lc_postNetworkWithRUL:(NSString *)url
                    parameter:(id)parameter
              responseSuccess:(void (^)(id resultCode, id))responseSuccessBlock
                 responseFail:(void (^)(id resultCode, NSError *error))responseFailBlock {
    

    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,url];
    [requestURL stringByReplacingOccurrencesOfString:@" " withString:@""];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[self requestToken] forHTTPHeaderField:@"Authorization"];
    
    [manager POST:requestURL parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        LCLog(@"服务器返回数据 = %@",responseObject);
        NSString *resultCode = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([url rangeOfString:@"login"].location != NSNotFound) {
            NSString *auth = [NSString stringWithFormat:@"%@",responseObject[@"token"]];
            [LCUserModel userModelManager].userid = auth;
            [[NSUserDefaults standardUserDefaults]setObject:auth forKey:@"token"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
        if ([resultCode isEqualToString:@"0"]) {
            NSDictionary *data = responseObject[@"data"];
            responseSuccessBlock(resultCode,data);
        }else{
            
            NSString *message = [NSString stringWithFormat:@"%@",responseObject[@"message"]];
            responseSuccessBlock(resultCode,message);
        }
        LCLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LCLog(@"error = %@",error.userInfo);

    }];
    
}

- (void)uploadFile {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[self requestToken] forHTTPHeaderField:@"Authorization"];
    
    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,@"/file/upload"];
//    UIImage *image = [UIImage imageNamed:@"yang"];
//    NSData *data = UIImageJPEGRepresentation(image, 0.1);

    NSDictionary *uploadParameter = @{@"path":@"/",@"file":@"yang"};
    [manager POST:requestURL parameters:uploadParameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LCLog(@"responseObject = %@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LCLog(@"error = %@",error);

    }];


}
- (void)uploadFile:(id)uploadFile
              Path:(NSString *)seriviceURL
          mimeType:(NSString *)mimeTypeStr
              name:(NSString *)nameStr
              Name:(NSString *)fileNameStr
         parameter:(id)uploadParameter
      successBlock:(void (^)(id sender))uploadSuccessBlock
         failBlock:(void (^)(id sender))uploadFailBlock
{
    NSData *uploadData = nil;
    if ([uploadFile isKindOfClass:[UIImage class]]) {
        /*image*/
        uploadData = UIImageJPEGRepresentation(uploadFile, 1);
    }else if ([uploadFile isKindOfClass:[NSString class]]){
        /*文件路径/文件名*/
        if ([uploadFile rangeOfString:@"/"].location != NSNotFound) {

            UIImage *uploadImage = [UIImage imageWithContentsOfFile:uploadFile];
            uploadData = UIImageJPEGRepresentation(uploadImage, 1);

        }else{

            UIImage *uploadImage = [UIImage imageNamed:uploadFile];
            uploadData = UIImageJPEGRepresentation(uploadImage, 1);

        }
    }else if ([uploadFile isKindOfClass:[NSData class]]){
        /*二进制文件*/
        uploadData = uploadFile;
    }
    LCLog(@"头像大小 %lu",(unsigned long)uploadData.length / 1024);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[self requestToken] forHTTPHeaderField:@"Authorization"];
    
//    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,@"/v0/user/avatar/update"];
    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,seriviceURL];

    seriviceURL = requestURL;
    [manager POST:seriviceURL parameters:uploadParameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:uploadData name:@"file" fileName:fileNameStr mimeType:mimeTypeStr];

        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        LCLog(@"进度 ");
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        LCLog(@"responseObject = %@",responseObject);
//        responseObject = {
//            errcode = 0;
//            message = success;
//        }
        uploadSuccessBlock(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        LCLog(@"error = %@",error);

        uploadFailBlock(error.userInfo);

    }];
    
}

///  
- (void)lc_uploadFileWithURL {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *requestURL = [NSString stringWithFormat:@"%@%@",BASEURL,@"/file/upload"];
     [manager POST:requestURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)lc_download {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURL *url = [NSURL URLWithString:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL URLWithString:@""];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
    }];
}

- (NSString *)requestToken {
    
    
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"token"]) {
        NSString *token = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]];
        return token;
    }else {
        return @"";
    }
}
@end
